package com.app.xinfadi.widget.image_browser.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;

import com.app.xinfadi.R;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.Toast;
import com.app.xinfadi.widget.image_browser.ImageExploreActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;


public class GridViewSquareImageBrowserAdapter extends BaseAdapter {
	private Context context;
	private ArrayList<String> imageUrl;
	/**
	 * 向 ImageExploreActivity 传送的数据 去掉拍照按钮
	 */
	private ArrayList<String> imageUrlComplete;

	public Bitmap bitmaps[];
	// private String dirPath;
	private List<View> holderlist;
	private int index = -1;
	private ImageSize mImageSize;
	private TreeMap<Integer, String> clickImages;

	protected String TAG = "GridViewSquareImageBrowserAdapter";
	private OnCheckChangeListener onCheckChangeListener;
	private OnPhotographClickListener onPhotographClickListener;
	/**
	 * 是否是所有图片
	 */
	private boolean isAllImages = false;
	private int selected_size;
	private DisplayImageOptions options;
	private int maxSize;

	public GridViewSquareImageBrowserAdapter(Context context, ArrayList<String> imageUrl, boolean isAllImages,
			int selected_size, int maxSize) {
		this.context = context;
		this.imageUrl = imageUrl;
		// this.dirPath = dirPath;
		bitmaps = new Bitmap[imageUrl.size()];
		holderlist = new ArrayList<View>();
		mImageSize = new ImageSize(270, 270);
		clickImages = new TreeMap<Integer, String>();
		this.isAllImages = isAllImages;
		this.selected_size = selected_size;
		this.maxSize = maxSize;
		options = new DisplayImageOptions.Builder().showImageOnFail(R.drawable.image_failed)
				.showImageOnLoading(R.drawable.image_failed).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.ARGB_4444).displayer(new SimpleBitmapDisplayer()).build();
		imageUrlComplete = new ArrayList<String>();

		for (String imageurl : imageUrl) {
			imageUrlComplete.add(imageurl);
		}
		if (isAllImages) {
			addPhotographImage(imageUrl);
			// 去掉拍照按钮
			// imageUrlComplete.remove(0);
		}

	}

	@Override
	public int getCount() {
		return imageUrl.size();
	}

	@Override
	public Object getItem(int position) {
		return imageUrl.get(position);
		// return null;
	}

	@Override
	public long getItemId(int id) {
		return id;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		// && convertView == null
		// if (position != index && position > index) {
		if (isAllImages && position == 0) {
			convertView = LayoutInflater.from(context).inflate(R.layout.image_browser_list_item, parent, false);
			holder = new ViewHolder();
			assert convertView != null;
			holder.common_image = (ImageView) convertView.findViewById(R.id.common_iamge);
			holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
			holder.common_black_bg = convertView.findViewById(R.id.common_black_bg);
			convertView.setTag(holder);
			holder.common_image.setTag(imageUrl.get(position));
		} else {
			if (convertView == null) {
				// 正常列表
				// index = position;
				convertView = LayoutInflater.from(context).inflate(R.layout.image_browser_list_item, parent, false);
				// view =
				// LayoutInflater.from(context).inflate(R.layout.image_browser_list_item,
				// null);
				holder = new ViewHolder();
				assert convertView != null;
				holder.common_image = (ImageView) convertView.findViewById(R.id.common_iamge);
				holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
				holder.common_black_bg = convertView.findViewById(R.id.common_black_bg);
				convertView.setTag(holder);
				holder.common_image.setTag(imageUrl.get(position));
				// holderlist.add(convertView);
			} else {
				holder = (ViewHolder) convertView.getTag();
				// holder = (ViewHolder) holderlist.get(position).getTag();
				// convertView = holderlist.get(position);
			}
		}
		// 选择所有图片
		if (isAllImages) {
			if (position == 0) {
				if (holder.common_image.getTag().equals(imageUrl.get(position))) {
					holder.common_image.setImageResource(R.drawable.image_photo);
					holder.checkBox.setVisibility(View.GONE);
				}
				holder.common_image.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (onPhotographClickListener != null) {
							onPhotographClickListener.onclick();
						}
					}
				});
			} else {
				initConvertView(holder.common_image, holder.checkBox, holder.common_black_bg, position);
			}
		} else {
			initConvertView(holder.common_image, holder.checkBox, holder.common_black_bg, position);
		}
		return convertView;
	}

	/**
	 * 添加拍照按钮
	 * 
	 * @param images
	 */
	private void addPhotographImage(List<String> images) {
		LogUtil.e(TAG, "添加拍照按钮");
		images.add(0, "拍照");
	}

	private void initConvertView(final ImageView common_image, CheckBox checkBox, final View common_black_bg,
			final int position) {
		common_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, ImageExploreActivity.class);
				Bundle bundle = new Bundle();
				bundle.putStringArrayList("imageUrlList", imageUrlComplete);
				if (isAllImages == true) {
					LogUtil.e(TAG, "isAllImages:" + isAllImages + " position:" + position);
					bundle.putInt("currentPosition", position - 1);
				} else {
					LogUtil.e(TAG, "isAllImages:" + isAllImages + " position:" + position);
					bundle.putInt("currentPosition", position);
				}
				intent.putExtras(bundle);
				context.startActivity(intent);
				// ImageLoader.getInstance().clearMemoryCache();
			}
		});
		// ImageLoader.getInstance().loadImage(imageUrl.get(position),
		// mImageSize, options,
		// new SimpleImageLoadingListener() {
		//
		// @Override
		// public void onLoadingComplete(String imageUri, View view, Bitmap
		// loadedImage) {
		// super.onLoadingComplete(imageUri, view, loadedImage);
		// // ImageView image = (ImageView)
		// // view1.findViewWithTag(imageUrl.get(position));
		// // image.setImageBitmap(loadedImage);
		// // if (imageUri.equals(common_image.getTag())) {
		// common_image.setImageBitmap(loadedImage);
		// // }
		// }
		// });
		// NonViewAware imageAware = new NonViewAware(imageUrl.get(position),
		// mImageSize, ViewScaleType.CROP);
		// if (common_image.getTag().equals(imageUrl.get(position)))
		common_image.setMaxHeight(370);
		common_image.setMaxWidth(370);
		ImageViewAware imageViewAware = new ImageViewAware(common_image);
		ImageLoader.getInstance().displayImage(imageUrl.get(position), imageViewAware, options);
		checkBox.setVisibility(View.VISIBLE);
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

				if (isChecked) {
					if (clickImages.size() >= maxSize - selected_size) {
						Toast.makeText(context, "你最多只能选择" + maxSize + "张图片", Toast.LENGTH_LONG).show();
						buttonView.setChecked(false);
					} else {
						common_black_bg.setVisibility(View.VISIBLE);
						clickImages.put(position, imageUrl.get(position));
						// LogUtil.e(TAG, "clickImages.add:" + position +
						// "");
						onCheckChangeListener.onCheckSize(clickImages.size());
					}
				} else {
					common_black_bg.setVisibility(View.GONE);
					clickImages.remove(position);
					LogUtil.e(TAG, "clickImages.remove:" + position + "");
					onCheckChangeListener.onCheckSize(clickImages.size());
				}
			}
		});
	}

	static class ViewHolder {
		ImageView common_image;
		CheckBox checkBox;
		View common_black_bg;
	}

	public List<String> getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(ArrayList<String> imageUrl) {
		this.imageUrl = imageUrl;
	}

	public ArrayList<String> getClickImages() {
		ArrayList<String> clickImagesList = new ArrayList<String>();
		// Get a set of entries
		Set<Entry<Integer, String>> set = clickImages.entrySet();
		// Get an iterator
		Iterator<Entry<Integer, String>> iterator = set.iterator();
		// Display elements
		while (iterator.hasNext()) {
			Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
			clickImagesList.add(String.valueOf(entry.getValue()));
		}
		return clickImagesList;
	}

	public interface OnCheckChangeListener {
		public void onCheckSize(int size);
	}

	public void setOnCheckChangeListener(OnCheckChangeListener onCheckChangeListener) {
		this.onCheckChangeListener = onCheckChangeListener;
	}

	/**
	 * 拍照 onClickListener
	 * 
	 * @Function: TODO <br/>
	 * @date 2015-2-9 下午5:49:10 <br/>
	 * @author WuTengFei <br/>
	 * 
	 */
	public interface OnPhotographClickListener {
		public void onclick();
	}

	public void setOnPhotographClickListener(OnPhotographClickListener onPhotographClickListener) {
		this.onPhotographClickListener = onPhotographClickListener;
	}

}